package com.dctp.ems.controller;

import com.dctp.common.controller.BaseController;
import com.dctp.common.vo.JsonResult;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

@Path("/richContent")
public class RichContentController extends BaseController {

    /**
     * 新增或更新
     * 参数: type, content
     */
    public void saveOrUpdate() {

        Record body = jsonBody();
        Integer type = body.getInt("type");
        String content = body.getStr("content");

        if (type == null || content == null) {
            renderJson(JsonResult.failWithMessage("参数不能为空"));
            return;
        }

        boolean ops = false;
        Record record = Db.findFirst("SELECT * FROM dctp_rich_content WHERE type = ?", type);
        if (record != null) {
            record.set("content", content);
            ops = Db.update("dctp_rich_content", record);
        } else {
            Record newRecord = new Record()
                    .set("type", type)
                    .set("content", content);
            ops = Db.save("dctp_rich_content", newRecord);
        }

        if (ops) {
            renderJson(JsonResult.success());
        }else {
            renderJson(JsonResult.failWithMessage("保存失败"));
        }
    }

    /**
     * 按类型查询
     * 参数: type
     */
    public void getContent() {
        Integer type = getParaToInt("type");

        if (type == null) {
            renderJson(JsonResult.failWithMessage("type不能为空"));
            return;
        }

        Record record = Db.findFirst("SELECT content FROM dctp_rich_content WHERE type = ?", type);
        String content = record != null ? record.getStr("content") : null;

        renderJson(JsonResult.successWithData(content));
    }
}
